package com.cqc.savenameandpwd;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;

public class MainActivity extends Activity {

	private AutoCompleteTextView autoCompleteTextView;
	private EditText editText;
	private SharedPreferences sp;
	private String[] keys;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		findViews();

		initSP();

		initView();
	}

	private void initView() {
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, keys);
		autoCompleteTextView.setAdapter(adapter);
		
		//用户名输入完成后自动填入密码
		autoCompleteTextView.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

			@Override
			public void afterTextChanged(Editable s) {
				String pwd = sp.getString(autoCompleteTextView.getText().toString().trim(), "");
				editText.setText(pwd);
			}
		});
	}

	//存放用户名和密码，和所有密码
	private void initSP() {
		//存放用户名和密码
		sp = getSharedPreferences("password", MODE_PRIVATE);
		sp.edit().putString("18100000001", "111111").putString("18100000002", "222222").putString("18100000003", "333333").putString("18100000004", "444444")
				.putString("18100000005", "555555").commit();
		//取出所有密码
		keys = new String[sp.getAll().size()];
		keys = sp.getAll().keySet().toArray(new String[5]);
	}

	private void findViews() {
		autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView);
		editText = (EditText) findViewById(R.id.editText);
	}
}
